<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\User;
use app\model\SystemConfig;
use PHPMailer\PHPMailer\PHPMailer;
use app\model\Note;
use app\model\Reminder;
use think\facade\View;

class TestController extends BaseController
{
    /**
     * 测试发送安全警告邮件
     */
    public function testSecurityEmail(Request $request)
    {
        try {
            $email = $request->param('email');
            if (empty($email)) {
                return json(['status' => 400, 'message' => '请提供测试邮箱地址']);
            }

            // 测试参数
            $testIp = '192.168.1.1';
            $isLongLock = $request->param('is_long_lock', false);
            $lockDuration = $isLongLock ? '24小时' : '30分钟';

            $mail = new PHPMailer(true);

            // 获取邮件配置
            $mailConfig = [
                'host' => SystemConfig::getConfig('mail_host'),
                'port' => SystemConfig::getConfig('mail_port'),
                'username' => SystemConfig::getConfig('mail_username'),
                'password' => SystemConfig::getConfig('mail_password'),
                'from' => SystemConfig::getConfig('mail_from'),
                'from_name' => SystemConfig::getConfig('mail_from_name'),
                'site_name' => SystemConfig::getConfig('site_name', '知更开放平台'),
                'site_url' => SystemConfig::getConfig('site_url')
            ];

            // 配置邮件服务器
            $mail->isSMTP();
            $mail->Host = $mailConfig['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $mailConfig['username'];
            $mail->Password = $mailConfig['password'];
            $mail->SMTPSecure = 'ssl';
            $mail->Port = $mailConfig['port'];
            $mail->CharSet = 'UTF-8';

            // 设置发件人和收件人
            $mail->setFrom($mailConfig['from'], $mailConfig['from_name']);
            $mail->addAddress($email);

            // 设置邮件内容
            $mail->Subject = "[{$mailConfig['site_name']}] 账号安全警告（测试邮件）";

            $mailContent = <<<EOT
            <div style="padding: 20px;">
                <h2>安全警告</h2>
                <p>您好，</p>
                <p>我们检测到您的账号存在异常登录尝试：</p>
                <ul>
                    <li>登录邮箱：{$email}</li>
                    <li>登录IP：{$testIp}</li>
                    <li>时间：{$this->getCurrentDateTime()}</li>
                </ul>
                <p>由于多次登录失败，您的账号已被临时锁定{$lockDuration}。</p>
                <p>如果这不是您的操作，建议您及时修改密码。</p>
                <div style="margin: 20px 0;">
                    <a href="{$mailConfig['site_url']}" 
                       style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">
                       访问系统
                    </a>
                    <a href="{$mailConfig['site_url']}/user/reset_password_page?email={$email}" 
                       style="background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block; margin-left: 10px;">
                       重置密码
                    </a>
                </div>
                <p>为了账号安全，请注意：</p>
                <ul>
                    <li>不要将密码告诉他人</li>
                    <li>使用复杂的密码组合</li>
                    <li>定期更换密码</li>
                    <li>不要在不安全的设备上登录</li>
                </ul>
                <p style="color: #666; margin-top: 20px;">
                    此邮件由系统自动发送，请勿回复。<br>
                    如有疑问，请访问 <a href="{$mailConfig['site_url']}" style="color: #007bff;">{$mailConfig['site_name']}</a>
                </p>
                <p style="color: #ff0000;">（这是一封测试邮件）</p>
            </div>
EOT;

            $mail->isHTML(true);
            $mail->Body = $mailContent;
            $mail->AltBody = strip_tags($mailContent);

            $mail->send();

            return json([
                'status' => 200, 
                'message' => '测试邮件发送成功',
                'data' => [
                    'email' => $email,
                    'lock_duration' => $lockDuration,
                    'send_time' => $this->getCurrentDateTime()
                ]
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('测试邮件发送失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '测试邮件发送失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取当前时间
     */
    private function getCurrentDateTime()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 测试项目创建
     */
    public function testCreateProject(Request $request)
    {
        try {
            // 测试数据
            $testData = [
                'name' => '测试项目_' . uniqid(),
                'goal' => '这是一个测试项目目标',
                'description' => '这是一个用于测试的项目描述',
                'category' => '测试分类',
                'start_date' => date('Y-m-d'),
                'duration' => 30
            ];

            // 直接创建请求对象并设置参数
            $projectRequest = new Request();
            $projectRequest->withPost($testData);
            $projectRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            // 正确初始化项目控制器，传入 app 实例
            $projectController = new \app\controller\ProjectController(app());
            $result = $projectController->create($projectRequest);
            
            return json([
                'status' => 200,
                'message' => '测试完成',
                'request_data' => $testData,
                'response_data' => $result
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试项目列表获取
     */
    public function testProjectList(Request $request)
    {
        try {
            // 测试不同参数组合
            $testCases = [
                ['status' => null, 'category' => null, 'desc' => '获取全部项目'],
                ['status' => 1, 'category' => null, 'desc' => '获取进行中的项目'],
                ['status' => 2, 'category' => null, 'desc' => '获取已完成的项目'],
                ['status' => 3, 'category' => null, 'desc' => '获取已暂停的项目']
            ];

            $results = [];
            $projectController = new \app\controller\ProjectController(app());

            foreach ($testCases as $case) {
                // 创建请求对象
                $projectRequest = new Request();
                $projectRequest->withGet($case);
                $projectRequest->withHeader([
                    'Authorization' => $request->header('Authorization')
                ]);

                $response = $projectController->index($projectRequest);
                $results[] = [
                    'description' => $case['desc'],
                    'response' => json_decode($response->getContent(), true)
                ];
            }

            return json([
                'status' => 200,
                'message' => '测试完成',
                'test_results' => $results
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试项目更新
     */
    public function testUpdateProject(Request $request)
    {
        try {
            $projectController = new \app\controller\ProjectController(app());

            // 先创建一个测试项目
            $createRequest = new Request();
            $createRequest->withPost(['name' => '测试更新项目_' . uniqid()]);
            $createRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            
            $createResult = $projectController->create($createRequest);
            $createData = json_decode($createResult->getContent(), true);
            
            if ($createData['status'] !== 200) {
                return json(['status' => 500, 'message' => '创建测试项目失败']);
            }

            $projectId = $createData['data']['id'];

            // 测试更新
            $updateRequest = new Request();
            $updateRequest->withPost([
                'id' => $projectId,
                'name' => '已更新的项目名称',
                'goal' => '已更新的项目目标',
                'description' => '已更新的项目描述'
            ]);
            $updateRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            $updateResult = $projectController->update($updateRequest);

            return json([
                'status' => 200,
                'message' => '测试完成',
                'create_result' => $createData,
                'update_result' => json_decode($updateResult->getContent(), true)
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试项目状态更新
     */
    public function testUpdateProjectStatus(Request $request)
    {
        try {
            $projectController = new \app\controller\ProjectController(app());

            // 先创建测试项目
            $createRequest = new Request();
            $createRequest->withPost(['name' => '测试状态项目_' . uniqid()]);
            $createRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            
            $createResult = $projectController->create($createRequest);
            $createData = json_decode($createResult->getContent(), true);
            
            if ($createData['status'] !== 200) {
                return json(['status' => 500, 'message' => '创建测试项目失败']);
            }

            $projectId = $createData['data']['id'];

            // 测试所有状态转换
            $statusTests = [
                ['status' => 1, 'desc' => '转为进行中'],
                ['status' => 2, 'desc' => '转为已完成'],
                ['status' => 3, 'desc' => '转为已暂停']
            ];

            $results = [];
            foreach ($statusTests as $test) {
                $statusRequest = new Request();
                $statusRequest->withPost([
                    'id' => $projectId,
                    'status' => $test['status']
                ]);
                $statusRequest->withHeader([
                    'Authorization' => $request->header('Authorization')
                ]);

                $response = $projectController->updateStatus($statusRequest);
                $results[] = [
                    'description' => $test['desc'],
                    'response' => json_decode($response->getContent(), true)
                ];
            }

            return json([
                'status' => 200,
                'message' => '测试完成',
                'project_id' => $projectId,
                'test_results' => $results
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试项目删除
     */
    public function testDeleteProject(Request $request)
    {
        try {
            $projectController = new \app\controller\ProjectController(app());

            // 先创建测试项目
            $createRequest = new Request();
            $createRequest->withPost(['name' => '测试删除项目_' . uniqid()]);
            $createRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            
            $createResult = $projectController->create($createRequest);
            $createData = json_decode($createResult->getContent(), true);
            
            if ($createData['status'] !== 200) {
                return json(['status' => 500, 'message' => '创建测试项目失败']);
            }

            $projectId = $createData['data']['id'];

            // 测试删除
            $deleteRequest = new Request();
            $deleteRequest->withPost(['id' => $projectId]);
            $deleteRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            $deleteResult = $projectController->delete($deleteRequest);

            // 验证删除后无法查看
            $checkRequest = new Request();
            $checkRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            $checkResult = $projectController->index($checkRequest);

            return json([
                'status' => 200,
                'message' => '测试完成',
                'create_result' => $createData,
                'delete_result' => json_decode($deleteResult->getContent(), true),
                'check_result' => json_decode($checkResult->getContent(), true)
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试笔记列表获取
     */
    public function testNoteList(Request $request)
    {
        try {
            // 创建请求对象
            $noteRequest = new Request();
            $noteRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            // 测试不同参数组合
            $testCases = [
                ['params' => [], 'desc' => '获取全部笔记'],
                ['params' => ['importance' => 1], 'desc' => '获取普通重要度笔记'],
                ['params' => ['importance' => 2], 'desc' => '获取重要笔记'],
                ['params' => ['source' => Note::SOURCE_USER], 'desc' => '获取用户手动记录的笔记']
            ];

            $results = [];
            $noteController = new \app\controller\NoteController(app());

            foreach ($testCases as $case) {
                $noteRequest->withGet($case['params']);
                $response = $noteController->index($noteRequest);
                $results[] = [
                    'description' => $case['desc'],
                    'response' => json_decode($response->getContent(), true)
                ];
            }

            return json([
                'status' => 200,
                'message' => '测试完成',
                'test_results' => $results
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试笔记创建
     */
    public function testNoteCreate(Request $request)
    {
        try {
            // 测试数据
            $testData = [
                'content' => '测试笔记内容_' . uniqid(),
                'importance' => Note::IMPORTANCE_NORMAL,
                'source' => Note::SOURCE_USER,
                'source_url' => 'https://example.com/test',
                'keywords' => ['测试', '笔记', 'test']
            ];

            // 创建请求对象
            $noteRequest = new Request();
            $noteRequest->withPost($testData);
            $noteRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            // 测试普通创建
            $noteController = new \app\controller\NoteController(app());
            $result = $noteController->create($noteRequest);

            // 测试使用Operation Key创建
            $reminder = Reminder::where('user_id', UserController::getUserFromToken($request)->id)
                ->find();
            
            $testDataWithKey = array_merge($testData, [
                'content' => '使用Operation Key创建的笔记_' . uniqid()
            ]);
            
            $noteRequestWithKey = new Request();
            $noteRequestWithKey->withPost($testDataWithKey);
            $noteRequestWithKey->withPost(['key'=> $reminder ? $reminder->operation_key : 'invalid_key']);
            
            $resultWithKey = $noteController->create($noteRequestWithKey);

            return json([
                'status' => 200,
                'message' => '测试完成',
                'test_results' => [
                    'normal_create' => json_decode($result->getContent(), true),
                    'operation_key_create' => json_decode($resultWithKey->getContent(), true)
                ]
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试笔记更新
     */
    public function testNoteUpdate(Request $request)
    {
        try {
            $noteController = new \app\controller\NoteController(app());

            // 先创建一个测试笔记
            $createRequest = new Request();
            $createRequest->withPost([
                'content' => '测试更新笔记_' . uniqid()
            ]);
            $createRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            
            $createResult = $noteController->create($createRequest);
            $createData = json_decode($createResult->getContent(), true);
            
            if ($createData['status'] !== 200) {
                return json(['status' => 500, 'message' => '创建测试笔记失败']);
            }

            $noteId = $createData['data']['id'];

            // 测试更新
            $updateRequest = new Request();
            $updateRequest->withPost([
                'id' => $noteId,
                'content' => '已更新的笔记内容',
                'importance' => Note::IMPORTANCE_IMPORTANT,
                'keywords' => ['更新', '测试']
            ]);
            $updateRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            $updateResult = $noteController->update($updateRequest);

            return json([
                'status' => 200,
                'message' => '测试完成',
                'create_result' => $createData,
                'update_result' => json_decode($updateResult->getContent(), true)
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试笔记删除
     */
    public function testNoteDelete(Request $request)
    {
        try {
            $noteController = new \app\controller\NoteController(app());

            // 先创建测试笔记
            $createRequest = new Request();
            $createRequest->withPost([
                'content' => '测试删除笔记_' . uniqid()
            ]);
            $createRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            
            $createResult = $noteController->create($createRequest);
            $createData = json_decode($createResult->getContent(), true);
            
            if ($createData['status'] !== 200) {
                return json(['status' => 500, 'message' => '创建测试笔记失败']);
            }

            $noteId = $createData['data']['id'];

            // 测试删除
            $deleteRequest = new Request();
            $deleteRequest->withParam('id', $noteId);
            $deleteRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            $deleteResult = $noteController->delete($deleteRequest);

            // 验证删除后无法查看
            $checkRequest = new Request();
            $checkRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            $checkResult = $noteController->index($checkRequest);

            return json([
                'status' => 200,
                'message' => '测试完成',
                'create_result' => $createData,
                'delete_result' => json_decode($deleteResult->getContent(), true),
                'check_result' => json_decode($checkResult->getContent(), true)
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 测试笔记AI总结
     */
    public function testNoteSummarize(Request $request)
    {
        try {
            $noteController = new \app\controller\NoteController(app());

            // 先创建一个测试笔记
            $createRequest = new Request();
            $createRequest->withPost([
                'content' => '这是一个需要AI总结的测试笔记内容。' . 
                           '包含了一些重要信息和关键点。' .
                           '可以测试AI的总结能力和关键词提取功能。'
            ]);
            $createRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);
            
            $createResult = $noteController->create($createRequest);
            $createData = json_decode($createResult->getContent(), true);
            
            if ($createData['status'] !== 200) {
                return json(['status' => 500, 'message' => '创建测试笔记失败']);
            }

            // 测试AI总结
            $summarizeRequest = new Request();
            $summarizeRequest->withParam('id', $createData['data']['id']);
            $summarizeRequest->withHeader([
                'Authorization' => $request->header('Authorization')
            ]);

            $summarizeResult = $noteController->summarize($summarizeRequest);

            return json([
                'status' => 200,
                'message' => '测试完成',
                'create_result' => $createData,
                'summarize_result' => json_decode($summarizeResult->getContent(), true)
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '测试失败：' . $e->getMessage()]);
        }
    }

    /**
     * 拍照上传测试页面
     */
    public function photo()
    {
        return View::fetch('test/photo');
    }
} 